package hjw.com.controller.adm;

import hjw.com.entity.Book;
import hjw.com.entity.LargeFile;
import hjw.com.service.BookServiceImpl;
import hjw.com.service.LargeFileServiceImpl;
import hjw.com.util.PackJsn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * <p>Project:Academic - AdmBookController
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/1/21 12:35
 * @since 1.8
 */
@RestController
@RequestMapping("/api/adm/book")
public class AdmBookController {

    private final Logger logger = LoggerFactory.getLogger(AdmBookController.class);
    private final BookServiceImpl bookDao;
    private final LargeFileServiceImpl largeFileDao;
    @Autowired(required = false)
    public AdmBookController(BookServiceImpl bookDao, LargeFileServiceImpl largeFileDao) {
        this.bookDao = bookDao;
        this.largeFileDao = largeFileDao;
    }

    @PostMapping("/findByPage")
    public String findByPage(@RequestBody Map<String, Object> map) {
        logger.info("===>findByPage="+map);
        if (map.get("pageNum") == null || map.get("lines") == null){
            return PackJsn.pack(203, "参数错误");
        }
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        int lines = Integer.parseInt(map.get("lines").toString());
        if ( pageNum < 1 || lines < 1){
            return PackJsn.pack(203, "参数错误");
        }

        int courPage = (pageNum-1)*lines;
        map.put("pageNum", courPage);
        List<Book> books = bookDao.findByParams(map);
        logger.info("books: " + books);
        if (books == null || books.isEmpty()){
            return PackJsn.pack(203, "库中无商品");
        }
        int count = bookDao.findByTypeCount(map);
        if (count == 0){
            return PackJsn.pack(203, "库中无商品");
        }
        Map<String, Object> returnMap = new HashMap<>(2);
        returnMap.put("count", count);
        returnMap.put("books", books);
        logger.info("returnMap: " + returnMap);
        return PackJsn.pack(200, "商品信息", returnMap);
    }

    @GetMapping("/findById/{id}")
    public String findById(@PathVariable("id") String id) {
        logger.info("===>findById="+id);
        if (id == null || id.isEmpty()){
            return PackJsn.pack(203, "参数错误");
        }
        Book book = bookDao.findById(id);
        logger.info("book: " + book);
        if (book == null){
            return PackJsn.pack(203, "库中无商品");
        }
        return PackJsn.pack(200, "商品信息", book);
    }

    @PostMapping("/updateAll")
    public String updateAll(@RequestParam Map<String, Object> map,
                            @RequestParam(value = "mypic", required = false) MultipartFile myfile) {
        String msg = "";
        String newPicId = "";
        int status = 0;


        String tmake = map.get("tmake").toString();
        logger.warn("===>上传过来的param："+map.get("tmake"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {

            Date date = sdf.parse(tmake);
            logger.warn("===>new出来的param："+date);
            map.put("tmake", date);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        logger.warn("===>param:"+map);

        if (myfile != null){
            UUID picId = UUID.randomUUID();
            newPicId = picId.toString().replace("-", "");
            LargeFile largeFile = null;
            try {
                largeFile = new LargeFile(newPicId, myfile.getOriginalFilename(), myfile.getBytes());
            } catch (IOException e) {
                return PackJsn.pack(203, "头像异常，请重新上传");
            }
            int add = largeFileDao.add(largeFile);
            if (add == 0){
                msg = "异常错误：1.头像上传失败 \n";
                map.remove("pic");
            }else {
                map.put("pic", newPicId);
                status = 1;
            }
            logger.info("头像上传成功：" + largeFile);
        }
        int id = Integer.parseInt(map.get("id").toString());
        if (id != 0){

            int update = bookDao.update(map);
            if (update == 0){
                if (status == 1){
                    largeFileDao.delete(newPicId);
                }
                msg += "异常错误：2.修改图书数据异常";
                return PackJsn.pack(203, msg);
            }
            return PackJsn.pack(200, "修改成功");
        }

        map.remove("id");
        int add = bookDao.add(map);
        if (add == 0){

            largeFileDao.delete(newPicId);
            msg += "异常错误：2.添加图书数据异常";
            return PackJsn.pack(203, msg);

        }
        return PackJsn.pack(203, "添加成功",Integer.parseInt(map.get("id").toString()));
    }

    @GetMapping("/del/{id}")
    public String del(@PathVariable("id") Integer id) {
        logger.info("===>del="+id);
        if (id == null || id == 0){
            return PackJsn.pack(203, "参数错误");
        }
        Book book = bookDao.findById(id.toString());
        if (book == null){
            return PackJsn.pack(203, "商品不存在");
        }
        if (book.getPic() != null){
            largeFileDao.delete(book.getPic());
        }
        int del = bookDao.delete(id);
        if (del == 0){
            return PackJsn.pack(203, "删除失败");
        }
        return PackJsn.pack(200, "删除成功");
    }
}
